package uk.org.brindy.osgi.fvis.bundle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.http.HttpService;

public class Activator implements BundleActivator {

	@SuppressWarnings("serial")
	public void start(BundleContext context) throws Exception {

		final BundleToJSON json = new BundleToJSON(context);

		HttpService httpService = (HttpService) context.getService(context
				.getServiceReference(HttpService.class.getName()));
		if (null == httpService) {
			throw new RuntimeException(
					"This bundle requires at least one running HttpService");
		}

		httpService.registerServlet("/"
				+ context.getBundle().getHeaders().get(
						Constants.BUNDLE_SYMBOLICNAME) + "/bundles.json",
				new HttpServlet() {
					@Override
					protected void doGet(HttpServletRequest req,
							HttpServletResponse resp) throws ServletException,
							IOException {
						resp.setContentType("text/json");
						resp.getWriter().println(json.toString());
					}
				}, null, null);

		httpService.registerResources("/"
				+ context.getBundle().getHeaders().get(
						Constants.BUNDLE_SYMBOLICNAME), "/bin-debug", null);

	}

	public void stop(BundleContext context) throws Exception {
	}

}
